﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace Ratatoskr.Toolbox
{
    class SquareCell : Cell
    {
        public SquareCell(int xLoc, int yLoc)
            : base(xLoc, yLoc, 8) { }

        protected internal override void FindAdjacentCells()
        {
            Grid<SquareCell> grid = _parent as Grid<SquareCell>;
            if (grid == null)
                throw new ArgumentNullException("Cannot find adjacent cells without a grid parent.");
            _adjacent = new Cell[8];
            bool leftmost = (_xLoc == grid.MinExtent.X);
            bool rightmost = (_xLoc == grid.MaxExtent.X);
            bool top = (_yLoc == grid.MinExtent.Y);
            bool bottom = (_yLoc == grid.MaxExtent.Y);
            if (!top)
            {
                _adjacent[0] = grid[_xLoc, _yLoc - 1];
                if (!rightmost)
                    _adjacent[1] = grid[_xLoc + 1, _yLoc - 1];
                if (!leftmost)
                    _adjacent[7] = grid[_xLoc - 1, _yLoc - 1];
            }
            if (!bottom)
            {
                _adjacent[4] = grid[_xLoc, _yLoc + 1];
                if (!rightmost)
                    _adjacent[3] = grid[_xLoc + 1, _yLoc + 1];
                if (!leftmost)
                    _adjacent[5] = grid[_xLoc - 1, _yLoc + 1];
            }
            if (!rightmost)
                _adjacent[2] = grid[_xLoc + 1, _yLoc];
            if (!leftmost)
                _adjacent[6] = grid[_xLoc - 1, _yLoc];
        }

        protected internal override CellPosition _CellStep(float x, float y)
        {
            Cell c = this;
            float x2 = x;
            float y2 = y;
            if (x > 0.5)
            {
                x2 -= 1;
                if (y > 0.5)
                {
                    y2 -= 1;
                    c = _adjacent[1];
                }
                else if (y < -0.5)
                {
                    y2 += 1;
                    c = _adjacent[7];
                }
                else c = _adjacent[0];
            }
            else if (x < -0.5)
            {
                x2 += 1;
                if (y > 0.5)
                {
                    y2 -= 1;
                    c = _adjacent[3];
                }
                else if (y < -0.5)
                {
                    y2 += 1;
                    c = _adjacent[5];
                }
                else c = _adjacent[4];
            }
            else if (y > 0.5)
            {
                y2 -= 1;
                c = _adjacent[2];
            }
            else if (y < -0.5)
            {
                y2 += 1;
                c = _adjacent[6];
            }
            if (c == null)
                return new CellPosition(this, x, y, true);
            return new CellPosition(c, x, y);
        }
    }
}
